package demo1;

//责任链模式 ：使多个对象都有机会处理请求，从而避免请求的发送者和接收者之间的耦合关系。
//将这个对象连成一条链，并沿着这条链传递请求，直到有一个对象处理它为止

public class Main {
    public static void main(String[] args) {
        Handler H1 = new ConcreteHandler1();
        Handler H2 = new ConcreteHandler2();
        Handler H3 = new ConcreteHandler3();
        H1.setSuccessor(H2);
        H2.setSuccessor(H3);

        int [] requests = {2,5,14,22,18,27,20};

        for (int request:requests
             ) {
            H1.HandRequest(request);
        }
    }
}

abstract class Handler{
    protected Handler successor;

    public void setSuccessor(Handler successor){
        this.successor = successor;
    }
    public abstract void HandRequest(int request);
}

class ConcreteHandler1 extends Handler{
    @Override
    public void HandRequest(int request) {
        if(request>=0 && request < 10){
            System.out.println("ConcreteHandler1 处理请求"+request);
        }else if(successor != null){
            successor.HandRequest(request);//转移到下一位
        }
    }
}

class ConcreteHandler2 extends Handler{
    @Override
    public void HandRequest(int request) {
        if(request >=10 && request<20){
            System.out.println("ConcreteHandler2 处理请求"+request);
        }else if(successor != null){
            successor.HandRequest(request);
        }
    }
}

class ConcreteHandler3 extends Handler{
    @Override
    public void HandRequest(int request) {
        if(request >=20 && request < 30){
            System.out.println("ConcreteHandler3 处理请求"+ request);
        }else if(successor != null){
            successor.HandRequest(request);
        }

    }
}